package com.igda.tihbms.data;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;

public class Sprite {

	private final byte[] sequence;
	private final Bitmap sprite;
	private final float spriteWidth;
	private final int spriteHeight;

	private final Rect src;
	private final RectF dst;

	private int sequenceIndex;
	private float angle;

	public Sprite(byte[] sequence, Bitmap spriteBitmap, int sprites) {
		this.sequence = sequence;
		this.sprite = spriteBitmap;
		this.spriteWidth = (float) spriteBitmap.getWidth() / sprites;
		this.spriteHeight = spriteBitmap.getHeight();

		this.src = new Rect();
		this.dst = new RectF();

		this.src.top = 0;
		this.src.bottom = this.spriteHeight;

		this.sequenceIndex = 0;
		this.angle = 0;
	}

	public void draw(Canvas canvas, float posX, float posY) {
		this.src.left = (int) (this.sequence[this.sequenceIndex] * this.spriteWidth);
		this.src.right = (int) (this.src.left + this.spriteWidth);

		this.dst.left = posX;
		this.dst.top = posY;
		this.dst.right = posX + this.spriteWidth;
		this.dst.bottom = posY + this.spriteHeight;

		canvas.rotate(this.angle, (this.dst.left + this.dst.right) / 2,
				(this.dst.top + this.dst.bottom) / 2);
		canvas.drawBitmap(this.sprite, this.src, this.dst, null);
		canvas.rotate(-this.angle, (this.dst.left + this.dst.right) / 2,
				(this.dst.top + this.dst.bottom) / 2);
	}

	public void toNext() {
		this.sequenceIndex++;
		this.sequenceIndex %= this.sequence.length;
	}

	public void rotate(float angle) {
		this.angle += angle;
	}

	public float getWidth() {
		return this.spriteWidth;
	}
}
